// pages/manage/activityManage/activityEdit/activityEdit.js
const {
    getActivityDetail,
    reSignLog,
    getStudentBySearch,
    getMajorBySearch,
    getDepartmentBySearch,
    getClassBySearch,
    getSignCode,
    completeActivity
} = require("../../../../utils/request/manage/activityManage/activityManage")
import Toast from 'tdesign-miniprogram/toast/index';
import ActionSheet, {
    ActionSheetTheme
} from 'tdesign-miniprogram/action-sheet/index';

var QRCode = require('../../../../utils/weapp-qrcode')
var qrcode;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        qrCodeData: '',
        activityInfo: {
            activityId: null,
            evaluate: '',
        },
        takeInStudents: [],
        authClass: [],
        classList: [],
        activityFinishVisible: false,
        classEmpty: {
            show: false,
            image: 'http://ldjy.asc.jx.cn/assets/draw_fly.png'
        },
        personEmpty: {
            show: false,
            image: 'http://ldjy.asc.jx.cn/assets/draw_fly.png'
        },
        studentList: [{
                name: '姓名一',
                userNumber: '08090520107'
            },
            {
                name: '姓名二',
                userNumber: '08090520108'
            }
        ],
        studentSearchForm: {
            pageSize: 80,
            pageNo: 1,
            name: '',
            departmentName: '',
            majorName: '',
            userNumber: ''
        },
        majorSearchForm: {},
        classSearchForm: {}
    },
    onTabsChange(event) {
        const tab = event.detail.value
        console.log(tab)
        switch (tab) {
            case '4':
                console.log('生成签到码')
                this.getScanCode();
                break;
            case 1: 
                break;
        }
    },



    // 根据活动ID获取信息
    getActivityById() {
        console.log('正在拉取活动信息')
        const activityId = wx.getStorageSync('activityEditId')
        getActivityDetail(activityId).then(res => {
            console.log(res)
            this.setData({
                activityInfo: res.data.activity,
                takeInStudents: res.data.takeInStudents,
                authClass: res.data.authClass,
                classList: res.data.classDTOS,
            })
        })
    },


    // 设置签到码
    createCode() {
        var that = this;
        new QRCode('myQrcode', {
            // text: 'http://ldjy.gnust.edu.cn/signCode' + this.data.qrCodeData,
            text: "http://192.168.1.108/signCode" + this.data.qrCodeData,
            //   text: '扫描内容',
            width: 150, //canvas 画布的宽
            height: 150, //canvas 画布的高
            padding: 0, // 生成二维码四周自动留边宽度，不传入默认为0
            correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
            colorDark: "#000", //分别为两种交替颜色
            colorLight: "white",
            callback: (res) => {
                //工具回调数据
                wx.hideLoading()
                console.log("生成二维码", res)
                //将图片路劲放入data中，显示在wxml的image标签上
                that.setData({
                    imagePath: res.path
                })
            }
        })
    },

    // 获取签到码
    getScanCode() {
        const activityId = this.data.activityInfo.activityId
        getSignCode(activityId).then(resp => {
            this.setData({
                qrCodeData: resp
            })
            console.log(resp)
            this.createCode()
        })
    },

    handleActivityAction(event) {
        ActionSheet.show({
            theme: ActionSheetTheme.List,
            selector: '#t-action-activity',
            context: this,
            align: 'left',
            description: '操作',
            items: [{
                    label: '撤销活动',
                    icon: 'delete-time',
                    suffixIcon: 'chevron-right',
                    color: '#ed7b2f',
                    action: 'removeActivity'
                },
                {
                    label: '完成活动',
                    icon: 'check-circle',
                    suffixIcon: 'chevron-right',
                    color: '#00a870',
                    action: 'finishActivity'
                },
                {
                    label: '修改活动',
                    icon: 'system-log',
                    suffixIcon: 'chevron-right',
                    action: 'editActivity'
                }
            ],
        });
    },
    handleRegisterAction(event) {
        console.log(event)
        ActionSheet.show({
            theme: ActionSheetTheme.List,
            selector: '#t-action-register',
            context: this,
            align: 'left',
            description: '操作',
            items: [{
                label: '报名活动',
                icon: 'check-circle',
                suffixIcon: 'chevron-right',
                color: '#00a870',
                action: 'handleRegister',
                data: event.currentTarget.dataset.item.userNumber
            }]
        })
    },
    handleStudentAction(event) {
        console.log(event)
        ActionSheet.show({
            theme: ActionSheetTheme.List,
            selector: '#t-action-students',
            context: this,
            align: 'left',
            description: '操作',
            items: [{
                    label: '移除人员',
                    icon: 'delete-time',
                    suffixIcon: 'chevron-right',
                    action: 'handleRemove',
                    color: '#ed7b2f',
                    data: event.currentTarget.dataset.item.userNumber
                },
                {
                    label: '手动补签',
                    icon: 'check-circle',
                    suffixIcon: 'chevron-right',
                    color: '#00a870',
                    action: 'handleSign',
                    data: event.currentTarget.dataset.item.userNumber
                }
            ],
        });
    },
    handleStudentsSelected(e) {
        console.log(e.detail)
        switch (e.detail.index) {
            case 0:
                this.handleRemove(e.detail.selected.data);
                break
            case 1:
                this.handleSign(e.detail.selected.data);
                break
        }
    },
    handleActivitySelected(e) {
        console.log(e.detail)
        switch (e.detail.index) {
            case 0:
                this.removeActivity(e.detail.selected.data);
                break
            case 1:
                this.onShowActivityFinish(e.detail.selected.data);
                break
            case 2:
                this.editActivity(e.detail.selected.data);
                break
        }
    },
    handleRegisterSelected(e) {
        console.log(e.detail)
        switch (e.detail.index) {
            case 0:
                this.handleRegister(e.detail.selected.data);
                break
        }
    },
    // 获取全部学生列表
    getStudentList() {
        console.log(this.data.studentSearchForm)
        getStudentBySearch(this.data.studentSearchForm).then(resp => {
            this.setData({
                studentList: resp.data.data.tableData
            })
        })
    },



    // 打开院系选择框
    onDepartmentPicker() {
        this.setData({
            departmentPicker: true
        })
        getDepartmentBySearch().then(res => {
            let modifiedData = res.data.data.tableData.map(item => {
                return {
                    label: item.departmentName,
                    value: item.departmentId
                };
            });
            // 使用 setData 方法更新数据
            this.setData({
                departmentTable: modifiedData
            });
        })
    },
    // 打开专业选择框
    onMajorPicker() {
        this.setData({
            majorPicker: true
        })
        const form = {
            departmentId: this.data.studentSearchForm.departmentId,
            pageSize: -1,
            pageNo: -1
        }
        getMajorBySearch(form).then(res => {
            let modifiedData = res.data.data.tableData.map(item => {
                return {
                    label: item.majorName,
                    value: item.majorId
                }
            })
            this.setData({
                majorTable: modifiedData
            })
        })
    },
    // 打开班级选择框
    onClassPicker() {
        this.setData({
            classPicker: true
        })
        const form = {
            departmentId: this.data.studentSearchForm.departmentId,
            majorId: this.data.studentSearchForm.majorId,
            pageSize: -1,
            pageNo: -1
        }
        getClassBySearch(form).then(res => {
            let modifiedData = res.data.data.tableData.map(item => {
                return {
                    label: item.className,
                    value: item.classId
                }
            })
            this.setData({
                classTable: modifiedData
            })
        })
    },
    // 选择院系
    onDepartmentChange(event) {
        this.setData({
            'studentSearchForm.departmentId': event.detail.value[0],
            'studentSearchForm.departmentName': event.detail.label[0]
        });
        this.getStudentList()
    },
    onMajorChange(event) {
        this.setData({
            'studentSearchForm.majorId': event.detail.value[0],
            'studentSearchForm.majorName': event.detail.label[0]
        })
        this.getStudentList()
    },
    onClassChange(event) {
        this.setData({
            'studentSearchForm.classId': event.detail.value[0],
            'studentSearchForm.className': event.detail.label[0]
        })
        this.getStudentList()
    },
    onDepartmentCancel() {
        this.setData({
            departmentPicker: false
        })
    },
    onMajorCancel() {
        this.setData({
            majorPicker: false
        })
    },
    onClasCancel() {
        this.setData({
            classPicker: false
        })
    },

    // 输入院系
    onDeptNameChange(e) {
        this.setData({
            'studentSearchForm.departmentName': e.detail.value
        })
        this.getStudentList()
    },
    // 输入专业
    onMajorNameChange(e) {
        this.setData({
            'studentSearchForm.majorName': e.detail.value
        })
        this.getStudentList()
    },
    // 输入学号
    onUserNumberChange(e) {
        this.setData({
            'studentSearchForm.userNumber': e.detail.value
        })
        this.getStudentList()
    },
    // 输入姓名
    onNameChange(e) {
        this.setData({
            'studentSearchForm.name': e.detail.value
        })
        this.getStudentList()
    },
    handleUserNumberInput(e) {
        const value = e.detail.value
        this.setData({
            'studentSearchForm.userNumber': value
        })
    },
    handleNameInput(e) {
        const value = e.detail.value
        this.setData({
            'studentSearchForm.name': value
        })
    },
    // 手动移除
    handleRemove(userNumber) {
        console.log(userNumber)
        const query = {
            userNumber: userNumber,
            activityId: this.data.activityInfo.activityId,
            signIn: -1
        }
        reSignLog(query).then(resp => {
            console.log(resp)
            if (resp.data.code === 200) {
                Toast({
                    context: this,
                    selector: '#t-toast',
                    message: '移除成功',
                    icon: 'check-circle',
                    direction: 'column',
                });
            }
        })
    },
    // 手动报名
    handleRegister(userNumber) {
        console.log(userNumber)
        const query = {
            userNumber: userNumber,
            activityId: this.data.activityInfo.activityId,
            signIn: 1
        }
        reSignLog(query).then(resp => {
            if (resp.data.code === 200) {
                Toast({
                    context: this,
                    selector: '#t-toast',
                    message: '报名成功',
                    icon: 'check-circle',
                    direction: 'column',
                });
            }
        })

    },
    // 手动签到
    handleSign(userNumber) {
        const query = {
            userNumber: userNumber,
            activityId: this.data.activityInfo.activityId,
            signIn: 2
        }
        reSignLog(query).then(resp => {
            if (resp.data.code === 200) {
                Toast({
                    context: this,
                    selector: '#t-toast',
                    message: '签到成功',
                    icon: 'check-circle',
                    direction: 'column',
                });
            }
        })
    },
    // 完成活动
    finishActivity() {
        const form = this.data.activityInfo
        completeActivity(form).then(resp => {
            if(res.data.code === 200){
                Toast({
                    context: this,
                    selector: '#t-toast',
                    message: '发布成功',
                    icon: 'check-circle',
                    direction: 'column',
                });
                
                wx.navigateTo({
                  url: '../activityManag',
                })

            }
        })
    },
    // 打开活动完成窗口
    onShowActivityFinish(){
        this.setData({
            activityFinishVisible: true
        })
    },
    // 关闭活动完成窗口
    onCloseActivityFinish(){
        this.setData({
            activityFinishVisible: false
        })
    },

    // 编辑活动
    editActivity() {

    },
    // 撤销活动
    removeActivity() {

    },
    handleAddImage() {

    },
    handleRemoveImage() {

    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getActivityById()
        this.getStudentList()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})